<?php

namespace Plugins\AdminBasic;

use App\Interfaces\AdminRolePermissionsCacheInterface;
use App\Interfaces\AdminRouteMenuServiceInterface;
use App\Interfaces\RequestLogInterface;
use Plugins\AdminBasic\Http\Admin\Service\Logins\AdministratorsLoginService;

class Install
{
    public static function run(): void
    {
        // 安装时需要的额外操作
        $dependenciesPath = BASE_PATH . '/config/autoload/dependencies.php';
        $dependencies = include $dependenciesPath;
        $interfaces = array_keys($dependencies);
        $replace = [];
        if (!in_array(AdminRouteMenuServiceInterface::class, $interfaces)) {
            $replace[] = <<<DEP
                // 后台菜单路由
                App\Interfaces\AdminRouteMenuServiceInterface::class => \Plugins\AdminBasic\Http\Admin\Service\RouteService::class,
            DEP;
        }
        if (!in_array(AdminRolePermissionsCacheInterface::class, $interfaces)) {
            $replace[] = <<<DEP
                // 权限缓存
                App\Interfaces\AdminRolePermissionsCacheInterface::class => \Plugins\AdminBasic\Http\Admin\Service\RolePermissionsService::class,
            DEP;
        }
        if (!in_array(RequestLogInterface::class, $interfaces)) {
            $replace[] = <<<DEP
                // 请求日志
                App\Interfaces\RequestLogInterface::class => \Plugins\AdminBasic\Http\Admin\Service\OperationLogsService::class,
            DEP;
        }
        if ($replace) {
            $dependencies = file_get_contents($dependenciesPath);
            $replace = implode("\n", $replace);
            $dependencies = preg_replace("/];\s*$/", <<<DEP
            $replace
            ];
            DEP
            , $dependencies);
            $res = file_put_contents($dependenciesPath, $dependencies);
            if ($res) {
                echo "dependencies.php 配置写入成功\n";
            }else{
                echo "dependencies.php 配置写入失败，请手动配置\n";
            }
        }

        $adminLoginPath = BASE_PATH . '/config/autoload/admin_login.php';
        $adminLogin = include $adminLoginPath;

        if (!in_array(AdministratorsLoginService::class, $adminLogin)) {
            $logins = file_get_contents(BASE_PATH . '/config/autoload/admin_login.php');
            if (array_key_exists('', $adminLogin)){
                $logins = preg_replace("/^\s*''\s*=>/m", "// $0", $logins);
                $logins = preg_replace("/^\s*\"\"\s*=>/m", "// $0", $logins);
            }

            $logins = preg_replace("/];\s*$/", <<<LOGIN
                '' => \Plugins\AdminBasic\Http\Admin\Service\Logins\AdministratorsLoginService::class,
            ];
            LOGIN
            , $logins);
            $res = file_put_contents($adminLoginPath, $logins);
            if ($res) {
                echo "admin_login.php 配置写入成功\n";
            }else{
                echo "admin_login.php 配置写入失败，请手动配置\n";
            }
        }
    }
}